//
//  CollectionViewController.m
//  KiklinkApp
//
//  Created by LJC on 14/10/21.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "CollectionViewController.h"

#import "ImagesManager.h"
#import "UIColor+hex.h"
#import "UIView+loadWithNib.h"

#import "MJRefresh.h"
#import "LocalCell.h"

#import "API.h"

#import "ProductViewController.h"

NSString *const collectionTableCellIdentifier = @"LocalCell";

@interface CollectionViewController ()
{
    //data
    NSMutableArray *collectionTableArray;
    NSInteger page;
    NSInteger totalPage;
    NSMutableDictionary *deleteDic;
    
    //ui
    UIBarButtonItem *deleteItem;
    UIBarButtonItem *confirmItem;
}
@end

@implementation CollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的收藏";
    self.view.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    
    
    //loading
    [self.activity startAnimating];
    self.refreshBtn.hidden = YES;
    [self.refreshBtn addTarget:self action:@selector(refresh) forControlEvents:UIControlEventTouchUpInside];
    
    
    //BundleImages
    ImagesManager *imagesManager = [ImagesManager sharedImagesManager];
    
    
    //leftNavItem
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setFrame:CGRectMake(0, 0, NavBarHeight/4, NavBarHeight/2)];
    [backButton setBackgroundImage:[imagesManager back] forState:UIControlStateNormal];
    [backButton setBackgroundImage:[imagesManager backTapped] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftNavBarItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftNavBarItem;
    
    
    //rightNavItem
    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [deleteButton setTitle:@"删除" forState:UIControlStateNormal];
    [deleteButton setTitleColor:[UIColor colorWithHexString:AppColor_Text] forState:UIControlStateNormal];
    deleteButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [deleteButton setFrame:CGRectMake(0, 0, NavBarHeight, NavBarHeight/2)];
    [deleteButton addTarget:self action:@selector(delete) forControlEvents:UIControlEventTouchUpInside];
    deleteItem = [[UIBarButtonItem alloc] initWithCustomView:deleteButton];
    
    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton setTitleColor:[UIColor colorWithHexString:AppColor_Text] forState:UIControlStateNormal];
    confirmButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [confirmButton setFrame:CGRectMake(0, 0, NavBarHeight, NavBarHeight/2)];
    [confirmButton addTarget:self action:@selector(confirm) forControlEvents:UIControlEventTouchUpInside];
    confirmItem = [[UIBarButtonItem alloc] initWithCustomView:confirmButton];

    self.navigationItem.rightBarButtonItem = deleteItem;
    
    
    //collectionTable
    [self.collectionTable setSeparatorInset:UIEdgeInsetsZero];
    self.collectionTable.separatorColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.collectionTable.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.collectionTable.delegate = self;
    self.collectionTable.dataSource = self;
    self.collectionTable.showsVerticalScrollIndicator = NO;
    [self.collectionTable registerClass:[UITableViewCell class] forCellReuseIdentifier:collectionTableCellIdentifier];
    [self setupRefresh];
    
    
    //data
    collectionTableArray = [[NSMutableArray alloc] init];
    deleteDic = [[NSMutableDictionary alloc] init];
    page = 1;
    [self getData:1 Condition:@"first"];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
    [self getData:1 Condition:@"header"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - get data
//condition:first&header&footer
- (void)getData:(NSInteger)pageNum Condition:(NSString *)condition
{
    NSLog(@"page:%ld",(long)pageNum);
    [API favouriteProductPageWithPageNumber:[NSNumber numberWithInteger:pageNum] Callback:^(int stateCode, NSString *word, id content) {
        
        if (stateCode == SUCCESS) {
            
            FavouriteItemPage *favouriteItemPage = (FavouriteItemPage *)content;
            NSMutableArray *result = [[NSMutableArray alloc] initWithArray:favouriteItemPage.result];
            
            if (favouriteItemPage.totalCount != 0) {
                self.collectionTable.scrollEnabled = YES;
                self.noCollection.hidden = YES;

                if ([condition isEqualToString:@"first"]) {
                    totalPage = favouriteItemPage.lastPageNumber;
                    page = 2;
                    collectionTableArray = result;
                } else if ([condition isEqualToString:@"header"]) {
                    page = 2;
                    collectionTableArray = result;
                } else if ([condition isEqualToString:@"footer"]) {
                    page ++;
                    [collectionTableArray addObjectsFromArray:result];
                }
                
                [self loadData:condition];
                
            } else {
                
                if ([condition isEqualToString:@"first"]) {
                    totalPage = favouriteItemPage.lastPageNumber;
                    self.collectionTable.scrollEnabled = NO;
                    self.noCollection.hidden = NO;
                    page = 2;
                    collectionTableArray = result;
                } else if ([condition isEqualToString:@"header"]) {
                    self.collectionTable.scrollEnabled = NO;
                    self.noCollection.hidden = NO;
                    page = 2;
                    collectionTableArray = result;
                } else if ([condition isEqualToString:@"footer"]) {
                    self.collectionTable.scrollEnabled = YES;
                    self.noCollection.hidden = YES;
                    page ++;
                    [collectionTableArray addObjectsFromArray:result];
                }
                
                [self loadData:condition];
                
            }

        } else {
            self.noCollection.hidden = YES;
            
            if ([condition isEqualToString:@"first"]) {
                self.collectionTable.scrollEnabled = NO;
                [self.activity stopAnimating];
                self.refreshBtn.hidden = NO;
            } else if ([condition isEqualToString:@"header"]) {
                self.collectionTable.scrollEnabled = YES;
                [self.collectionTable headerEndRefreshing];
            } else if ([condition isEqualToString:@"footer"]) {
                self.collectionTable.scrollEnabled = YES;
                [self.collectionTable footerEndRefreshing];
            }
            
        }
        
    }];

}

- (void)loadData:(NSString *)condition
{
    [self.collectionTable reloadData];
    self.collectionTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    if ([condition isEqualToString:@"first"]) {
        [self.activity stopAnimating];
    } else if ([condition isEqualToString:@"header"]) {
        [self.collectionTable headerEndRefreshing];
    } else if ([condition isEqualToString:@"footer"]) {
        [self.collectionTable footerEndRefreshing];
    }
}

- (void)refresh
{
    self.refreshBtn.hidden = YES;
    [self.activity startAnimating];
    
    [self getData:1 Condition:@"first"];
}
#pragma mark - get data End

#pragma mark - delete collection
- (void)deleteCollection
{
    NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithDictionary:deleteDic];
    [deleteDic removeAllObjects];
    for (NSNumber *collectionId in [temp allKeys]) {
       
        [API removeFavouriteItemWithFavouriteId:collectionId Callback:^(int stateCode, NSString *word, id content) {}];
        
    }
    [self.collectionTable setEditing:NO animated:YES];
    [self getData:1 Condition:@"header"];
}
#pragma mark - delete collection End

#pragma mark - back
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - back End

#pragma mark - edit
- (void)delete
{
    self.navigationItem.rightBarButtonItem = confirmItem;
    [self.collectionTable setEditing:YES animated:YES];
}
- (void)confirm
{
    self.navigationItem.rightBarButtonItem = deleteItem;
    [self deleteCollection];
}
#pragma mark - edit End

#pragma tableView dataSource&delegate  &MJRefresh
- (void)setupRefresh
{
    [self.collectionTable addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.collectionTable addFooterWithTarget:self action:@selector(footerRereshing)];
    
    self.collectionTable.headerPullToRefreshText = @"下拉可以刷新";
    self.collectionTable.headerReleaseToRefreshText = @"松开马上刷新";
    self.collectionTable.headerRefreshingText = @"正在刷新...";
    self.collectionTable.footerPullToRefreshText = @"上拉加载更多";
    self.collectionTable.footerReleaseToRefreshText = @"松开马上加载";
    self.collectionTable.footerRefreshingText = @"正在加载...";
}
- (void)headerRereshing
{
    //data
    [self getData:1 Condition:@"header"];
}
- (void)footerRereshing
{
    //data
    if (page <= totalPage) {
        [self getData:page Condition:@"footer"];
    } else {
        [self.collectionTable footerEndRefreshing];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return collectionTableArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        UINib *nib = [UINib nibWithNibName:@"LocalCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:collectionTableCellIdentifier];
        nibsRegistered = YES;
    }
    LocalCell *cell = (LocalCell *)[tableView dequeueReusableCellWithIdentifier:collectionTableCellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    [cell loadDataWithFavouriteItem:[collectionTableArray objectAtIndex:indexPath.row]];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 96;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.navigationItem.rightBarButtonItem == confirmItem) {
        FavouriteItem *favouriteItem = (FavouriteItem *)[collectionTableArray objectAtIndex:indexPath.row];
        [deleteDic setObject:indexPath forKey:favouriteItem.id];
    } else {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        ProductViewController *productVC = [[ProductViewController alloc] init];
        FavouriteItem *corFavouriteItem = [collectionTableArray objectAtIndex:indexPath.row];
        productVC.productID = [corFavouriteItem.targetId integerValue];
        [self.navigationController pushViewController:productVC animated:YES];
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.navigationItem.rightBarButtonItem == confirmItem) {
        FavouriteItem *favouriteItem = (FavouriteItem *)[collectionTableArray objectAtIndex:indexPath.row];
        [deleteDic removeObjectForKey:favouriteItem.id];
    }
}
#pragma tableView dataSource&delegate End

@end
